package glazedlists.chapter1;

import ca.odell.glazedlists.BasicEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.swing.DefaultEventListModel;
import ca.odell.glazedlists.swing.GlazedListsSwing;
import ca.odell.issuezilla.Issue;
import ca.odell.issuezilla.IssuezillaXMLParser;

import javax.swing.*;
import java.awt.*;
import java.io.InputStream;
import java.util.Collection;

public class IssuesBrowser1 {

    private EventList<Issue> issueEventList = new BasicEventList<>();

    public IssuesBrowser1(Collection<Issue> issues) {
        issueEventList.addAll(issues);
    }

    public void display() {
        JPanel panel = new JPanel(new GridBagLayout());
        DefaultEventListModel<Issue> listModel = GlazedListsSwing.eventListModelWithThreadProxyList(issueEventList);
        JList<Issue> issueJList = new JList<>(listModel);
        JScrollPane issuesListScrollPane = new JScrollPane(issueJList);
        panel.add(issuesListScrollPane,
                new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
                        new Insets(5, 5, 5, 5), 0, 0));

        JFrame frame = new JFrame("Issues");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(540, 380);
        frame.getContentPane().add(panel);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        final Collection<Issue> issues;
        IssuezillaXMLParser parser = new IssuezillaXMLParser();
        try (InputStream inputStream = IssuesBrowser1.class.getResourceAsStream("/issues.xml")) {
            issues = parser.loadIssues(inputStream, null);
        } catch (Exception ex) {
            ex.printStackTrace();
            return;
        }

        SwingUtilities.invokeLater(() -> {
            IssuesBrowser1 browser = new IssuesBrowser1(issues);
            browser.display();
        });
    }
}
